/******************************************************************************************************
Copyright (C) 2017 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals mainWindow, qsTr, serialization, settings, Application, MessageBox, ProgressDialog, MnUi*/
/*jslint plusplus: true, indent: 4, continue: true*/

function multiOpenList() {
	"use strict";

	var i, dialog, filesList, data, showDialog, oldFileHistory, document,
		docsToMerge, flagIssue, flagAImport, progressDialog, textFiles,
		filesListKey = "Multi Open List/File list",
		optMultiDocsKey = "Multi Open List/Mnova Multidocs Open";

	/**********************AUXILIARY FUNCTIONS********************/
	function createNewDocByReusing() {
		var auxDocs, doc, k;

		auxDocs = Application.mainWindow.documents();
		if (auxDocs.length > 0) {
			for (k = 0; k < auxDocs.length; k++) {
				doc = -1;
				if (auxDocs[k].isValid() && auxDocs[k].itemCount() === 0) {
					doc = auxDocs[k];
					break;
				}
			}
			if (doc === undefined || doc === -1) {
				doc = Application.mainWindow.newDocument();
			}
		} else {
			doc = Application.mainWindow.newDocument();
		}
		return doc;
	}

	function appendDocument(aArray) {

		var i, flagIssue;

		flagIssue = true;
		for (i = 0; i < aArray.length; ++i) {
			if (!serialization.open(aArray[i], "mnpag")) {
				flagIssue = false;
			}
			Application.mainWindow.activeDocument.setCurPageIndex(Application.mainWindow.activeDocument.pageCount() - 1); //to append the new document at the end
		}

		return flagIssue;
	}

	/**********************MAIN PROGRAM********************/

	//Load UI and initialize vars
	dialog = Application.loadUiFile('ricares:multiOpenList.ui');
	dialog.show();
	flagIssue = false;
	flagAImport = false;

	//Load registry values
	data = settings.value(filesListKey, "");
	if (data !== "") {
		dialog.widgets.plainTextEditFilesList.plainText = data;
	}

	data = settings.value(optMultiDocsKey, "");
	if (data !== "") {
		data = (data === "true");
		dialog.widgets.checkBoxSingleDocument.checked = data;
	}

	//Manage the dialog options
	showDialog = true;
	while (showDialog) {

		//Check if cancle button is pulsed by user
		if (!dialog.exec()) {
			return;
		}

		//Lile list control errors
		if (dialog.widgets.plainTextEditFilesList.plainText.toString().trim() === "" ) {
			MessageBox.critical(qsTr("File list does not exist"));
			continue;
		}

		showDialog = false;
	}

	//Get the list of files
	textFiles = dialog.widgets.plainTextEditFilesList.plainText;
	if (textFiles[textFiles.length - 1] === "\n") {
		textFiles = textFiles.substring(0, textFiles.length - 1);
	}
	filesList = textFiles.split("\n");
	oldFileHistory = serialization.fileHistory;
	serialization.fileHistory = false;

	//Initalize progresss bar
	progressDialog = new ProgressDialog();
	progressDialog.visible = true;
	progressDialog.minimum = 0;
	progressDialog.maximum = 100;
	progressDialog.value = 0;

	//If is enabled the option to work in a single document. We create a new document for the result and we clone all pages to this document
	if (dialog.widgets.checkBoxSingleDocument.checked) {

		//Create the result doc if we coudn't reuse it because it is not blank
		document = createNewDocByReusing();
		document.deletePages(document.pages());

		//For all mnova document
		for (i = 0; i < filesList.length && !progressDialog.wasCanceled; i++) {

			progressDialog.labelText = "Importing files (" + (i + 1) + " of " + filesList.length + ")";
			progressDialog.value = (i / filesList.length) * 100;
			progressDialog.update();
			mainWindow.processEvents();

			if (filesList[i].toString().toLowerCase().indexOf("mnova", filesList[i].toString().length - "mnova".length) !== -1) {

				//We push it into the mnova stack paths
				docsToMerge = [];
				docsToMerge.push(filesList[i]);
				if (!appendDocument(docsToMerge)) {
					flagIssue = true;
				} else {
					flagAImport = true;
				}

			} else {
				if (!serialization.open(filesList[i])) {
					flagIssue = true;
				} else {
					flagAImport = true;
				}
			}
		}

		//Set the result document to active and put the optional files at the end of the result document
		Application.mainWindow.activeDocument = document;

	} else {

		//We open all files at once
		for (i = 0; i < filesList.length && !progressDialog.wasCanceled; i++) {

			progressDialog.labelText = "Importing files (" + (i + 1) + " of " + filesList.length + ")";
			progressDialog.value = (i / filesList.length) * 100;
			progressDialog.update();
			mainWindow.processEvents();

			if (!serialization.open(filesList[i])) {
				flagIssue = true;
			} else {
				flagAImport = true;
			}
		}
	}

	//End progreess dialog
	progressDialog.value = 100;
	progressDialog.visible = false;

	//Show messages if something wrong has happened
	if (!flagAImport) {
		MessageBox.critical("The import process has not been performed");
	} else if (flagIssue) {
		MessageBox.information("Some of the files could not be imported");
	}

	//Save registry values
	serialization.fileHistory = oldFileHistory;
	settings.setValue(filesListKey, dialog.widgets.plainTextEditFilesList.plainText);
	settings.setValue(optMultiDocsKey, dialog.widgets.checkBoxSingleDocument.checked);
}

if (this.MnUi && MnUi.scripts_common) {
	MnUi.scripts_common.scripts_common_MultiOpenList = multiOpenList;
}
